// 页面加载完成后检测表单
document.addEventListener('DOMContentLoaded', () => {
    detectLoginForms();
});

// 动态监听DOM变化，处理动态加载的表单
const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        if (mutation.addedNodes.length) {
            detectLoginForms();
        }
    });
});

observer.observe(document.body, {
    childList: true,
    subtree: true
});

function detectLoginForms() {
    // 查找所有表单
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        // 如果表单已经处理过，跳过
        if (form.dataset.passwordManagerProcessed) return;
        
        const passwordField = form.querySelector('input[type="password"]');
        if (passwordField) {
            // 标记表单已处理
            form.dataset.passwordManagerProcessed = 'true';
            setupFormListener(form);
            
            // 尝试自动填充
            tryAutoFill(form);
        }
    });

    // 处理无表单的登录页面
    const passwordFields = document.querySelectorAll('input[type="password"]');
    passwordFields.forEach(passwordField => {
        if (!passwordField.form && !passwordField.dataset.passwordManagerProcessed) {
            passwordField.dataset.passwordManagerProcessed = 'true';
            setupPasswordFieldListener(passwordField);
        }
    });
}

function setupPasswordFieldListener(passwordField) {
    const container = passwordField.parentElement;
    const usernameField = findUsernameField(container);

    if (usernameField) {
        container.addEventListener('submit', (e) => {
            handleCredentialsSave(usernameField, passwordField);
        });

        // 监听回车键
        passwordField.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                handleCredentialsSave(usernameField, passwordField);
            }
        });

        // 尝试自动填充
        tryAutoFill(container);
    }
}

function setupFormListener(form) {
    const passwordField = form.querySelector('input[type="password"]');
    const usernameField = findUsernameField(form);

    if (passwordField && usernameField) {
        // 监听表单提交
        form.addEventListener('submit', (e) => {
            handleCredentialsSave(usernameField, passwordField);
        });

        // 监听按钮点击
        const submitButtons = form.querySelectorAll('button[type="submit"], input[type="submit"]');
        submitButtons.forEach(button => {
            button.addEventListener('click', () => {
                handleCredentialsSave(usernameField, passwordField);
            });
        });
    }
}

function findUsernameField(container) {
    // 常见的用户名/邮箱输入字段选择器
    const usernameSelectors = [
        'input[type="email"]',
        'input[type="text"]',
        'input[name*="email"]',
        'input[name*="user"]',
        'input[id*="email"]',
        'input[id*="user"]',
        'input[name*="login"]',
        'input[id*="login"]',
        'input[autocomplete="username"]'
    ];

    for (const selector of usernameSelectors) {
        const field = container.querySelector(selector);
        if (field && isVisible(field)) {
            return field;
        }
    }

    // 如果没有找到，尝试查找密码字段之前的文本输入框
    const passwordField = container.querySelector('input[type="password"]');
    if (passwordField) {
        const allInputs = Array.from(container.querySelectorAll('input[type="text"], input[type="email"]'));
        const previousInput = allInputs.find(input => 
            input.compareDocumentPosition(passwordField) & Node.DOCUMENT_POSITION_FOLLOWING
        );
        if (previousInput && isVisible(previousInput)) {
            return previousInput;
        }
    }

    return null;
}

function isVisible(element) {
    return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length);
}

async function handleCredentialsSave(usernameField, passwordField) {
    if (!usernameField.value || !passwordField.value) return;

    const credentials = {
        username: usernameField.value,
        password: passwordField.value,
        website: window.location.origin,
        timestamp: new Date().toISOString()
    };

    // 检查是否已存在相同的凭据
    const exists = await checkExistingCredentials(credentials);
    if (!exists) {
        // 显示保存提示
        showSavePrompt(credentials);
    }
}

function checkExistingCredentials(credentials) {
    return new Promise(resolve => {
        chrome.runtime.sendMessage({
            action: 'checkCredentials',
            data: credentials
        }, response => {
            resolve(response && response.exists);
        });
    });
}

function tryAutoFill(container) {
    chrome.runtime.sendMessage({
        action: 'getCredentials',
        url: window.location.origin
    }, response => {
        if (response && response.credentials) {
            autoFillCredentials(container, response.credentials);
        }
    });
}

function autoFillCredentials(container, credentials) {
    const usernameField = findUsernameField(container);
    const passwordField = container.querySelector('input[type="password"]');

    if (usernameField && passwordField) {
        // 添加自动填充按钮
        addAutoFillButton(container, credentials, usernameField, passwordField);

        // 如果只有一组凭据，直接填充
        if (!Array.isArray(credentials)) {
            usernameField.value = credentials.username;
            passwordField.value = credentials.password;
        }
    }
}

function addAutoFillButton(container, credentials, usernameField, passwordField) {
    const button = document.createElement('button');
    button.textContent = '自动填充密码';
    button.style.cssText = `
        position: absolute;
        right: 10px;
        background: #4CAF50;
        color: white;
        border: none;
        padding: 5px 10px;
        border-radius: 4px;
        cursor: pointer;
        z-index: 10000;
    `;

    // 根据密码字段位置放置按钮
    const rect = passwordField.getBoundingClientRect();
    button.style.top = `${rect.top + window.scrollY - 30}px`;

    button.onclick = () => {
        if (Array.isArray(credentials)) {
            showCredentialsList(credentials, usernameField, passwordField);
        } else {
            usernameField.value = credentials.username;
            passwordField.value = credentials.password;
        }
    };

    document.body.appendChild(button);
}

function showCredentialsList(credentialsList, usernameField, passwordField) {
    const list = document.createElement('div');
    list.style.cssText = `
        position: absolute;
        background: white;
        border: 1px solid #ccc;
        border-radius: 4px;
        padding: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        z-index: 10001;
    `;

    credentialsList.forEach(cred => {
        const item = document.createElement('div');
        item.style.padding = '5px';
        item.style.cursor = 'pointer';
        item.textContent = cred.username;
        item.onclick = () => {
            usernameField.value = cred.username;
            passwordField.value = cred.password;
            list.remove();
        };
        list.appendChild(item);
    });

    // 放置在密码字段下方
    const rect = passwordField.getBoundingClientRect();
    list.style.top = `${rect.bottom + window.scrollY + 5}px`;
    list.style.left = `${rect.left + window.scrollX}px`;

    document.body.appendChild(list);

    // 点击外部关闭列表
    document.addEventListener('click', function closeList(e) {
        if (!list.contains(e.target)) {
            list.remove();
            document.removeEventListener('click', closeList);
        }
    });
}

function showSavePrompt(credentials) {
    const prompt = document.createElement('div');
    prompt.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: white;
        padding: 15px;
        border-radius: 5px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        z-index: 10000;
        font-family: Arial, sans-serif;
    `;
    
    prompt.innerHTML = `
        <div style="margin-bottom: 10px;">是否保存此网站的密码？</div>
        <div style="color: #666; margin-bottom: 10px;">
            网站: ${credentials.website}<br>
            用户名: ${credentials.username}
        </div>
        <div style="display: flex; gap: 10px;">
            <button id="savePass" style="
                background: #4CAF50;
                color: white;
                border: none;
                padding: 5px 10px;
                border-radius: 4px;
                cursor: pointer;
            ">保存</button>
            <button id="cancelPass" style="
                background: #f44336;
                color: white;
                border: none;
                padding: 5px 10px;
                border-radius: 4px;
                cursor: pointer;
            ">取消</button>
        </div>
    `;
    
    document.body.appendChild(prompt);
    
    // 添加按钮事件
    prompt.querySelector('#savePass').onclick = () => {
        chrome.runtime.sendMessage({
            action: 'saveCredentials',
            data: credentials
        }, () => {
            prompt.remove();
        });
    };
    
    prompt.querySelector('#cancelPass').onclick = () => {
        prompt.remove();
    };
    
    // 10秒后自动移除提示
    setTimeout(() => {
        if (document.body.contains(prompt)) {
            prompt.remove();
        }
    }, 10000);
}
